<template>
  <el-drawer
    :title="title"
    v-model="visible"
    :direction="direction"
    :size="800"
    :before-close="beforeClose"
  >
    <section class="drawer-main">
      <el-form
        label-position="left"
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
      >
        <el-form-item label="订阅模式" prop="subscribeType">
          <el-select
            v-model="ruleForm.subscribeType"
            placeholder="请选择订阅模式"
          >
            <el-option
              v-for="(item, index) in modeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="回调地址"
          prop="callbackUrl"
          v-if="ruleForm.subscribeType == 'CALLBACK'"
        >
          <el-input v-model="ruleForm.callbackUrl" />
        </el-form-item>
      </el-form>
      <!-- 说明 -->
      <div class="desc">
        <h3>备注：</h3>
        <h5>请求方式</h5>
        <p>POST</p>
        <h5>Content-Type</h5>
        <p>application/json</p>
        <h5>body</h5>
        <table class="params">
          <tr>
            <th>参数</th>
            <th>参数名称</th>
            <th>类型</th>
            <th>必填</th>
            <th>备注</th>
          </tr>
          <tr>
            <td>data</td>
            <td>内容</td>
            <td>String</td>
            <td>是</td>
            <td>备注</td>
          </tr>
        </table>
        <h5>返回示例</h5>
        <code>
          <pre>
            {
                "code": "200",
                "message": "请求成功",
                "success": "true",
                "data": {
                }
            }
          </pre>
        </code>
      </div>
      <ReturnValueEntering
        v-if="!dataLoading"
        v-model="ruleForm.paramsMap"
        @insert="insertLine"
      />
      <h3>推送条件</h3>
      <PushCondtion  v-if="!dataLoading" v-model="ruleForm.conditionJson" @insert="insertJosn" />
    </section>

    <footer class="drawer-footer">
      <el-button @click="beforeClose">取 消</el-button>
      <el-button type="primary" @click="submit" :loading="loading">
        确 定
      </el-button>
    </footer>
  </el-drawer>
</template>

<script>
import { defineComponent, watch, computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { createAppMode } from "@/api/application";
import useEditDrawer from "@/hooks/useEditDrawer";
import ReturnValueEntering from "@/components/ReturnValueEntering/";
import PushCondtion from "@/components/ReturnValueEntering/PushCondtion.vue";
export default defineComponent({
  name: "ModeDrawer",
  emits: ["update:modelValue", "update-list"],
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "",
    },
    item: {
      type: Object,
      default: () => {},
    },
  },
  components: { ReturnValueEntering, PushCondtion },
  setup(props, { emit }) {
    // 表单
    const DEFAULT_FORM = {
      id: null,
      callbackUrl: null,
      subscribeType: null,
    };
    const dataLoading = ref(false);
    // 验证
    const rules = computed(() => {
      return {};
    });

    const {
      visible,
      direction,
      loading,
      ruleForm,
      ruleFormRef,
      close,
      beforeClose,
      title,
    } = useEditDrawer({
      createApi: createAppMode,
      editApi: createAppMode,
      defaultForm: DEFAULT_FORM,
      emit,
      type: props.type,
      props,
    });
    // 数据库类型
    const modeList = ref([
      {
        label: "回调",
        value: "CALLBACK",
      },
      {
        label: "监听",
        value: "LISTEN",
      },
    ]);
    const insertLine = (arr) => {
      console.log("insertLine", arr);
      const paramsMap = insertAddLine(arr);
      ruleForm.value.paramsMap = [...paramsMap];
    };
    const insertJosn = (arr) => {
      console.log("insertJosn", arr);
      const paramsMap = insertAddJson(arr);
      ruleForm.value.conditionJson = [...paramsMap];
    };

    const insertAddLine = (arr) => {
      const result = arr == null ? [] : [...arr];
      result.push({
        jsonSource: null,
        jsonTarget: null,
      });
      return result;
    };

    const insertAddJson = (arr) => {
      const result = arr == null ? [] : [...arr];
      result.push({
        key: null,
        value: null,
      });
      return result;
    };

    // 显示时赋值
    watch(visible, async (value) => {
      if (value) {
        dataLoading.value = true;
        ruleForm.value = {
          ...DEFAULT_FORM,
          ...props.item,
        };
        let paramsList = ruleForm.value.paramsMap;
        if (paramsList == null || paramsList.length == 0) {
          paramsList = insertAddLine(paramsList);
          ruleForm.value.paramsMap = [...paramsList];
          console.log( ruleForm.value.paramsMap);
        }
        // 推送条件
        let josnList = ruleForm.value.conditionJson;
        if (josnList == null || josnList.length == 0) {
          josnList = insertAddJson(josnList);
          ruleForm.value.conditionJson = [...josnList];
        }

        dataLoading.value = false;
      } else {
        dataLoading.value = false;
      }
    });
    const isNullString = (str) => {
      return (
        str == undefined ||
        str == null ||
        str.replace(/(^\s*)|(\s*$)/g, "").length == 0
      );
    };
    // 新增
    const createFn = async () => {
      const params = { ...ruleForm.value };
      let canSend = true; // 是否可以提交
      for (let i = 0; i < params.paramsMap.length; i++) {
        const item = params.paramsMap[i];
        const sourceIsNull = isNullString(item.jsonSource);
        const targetIsNull = isNullString(item.jsonTarget);
        // 都为空删掉
        if (sourceIsNull && targetIsNull) {
          params.paramsMap.splice(i, 1);
          i--;
          // 有一个为空提示补齐
        } else if (sourceIsNull || targetIsNull) {
          canSend = false;
          break;
        }
      }
         // 推送条件
      params.conditionJson.splice(-1, 1);
      params.conditionJson.map((item, index) => {
        if (!item.key || !item.value || !item.operator) {
          canSend = false;
          return false;
        }
      });
      if (canSend) {
        loading.value = true;
        const res = await createAppMode(params);
        loading.value = false;
        if (res.status === 200 || res.status === 201) {
          ElMessage.success("保存成功");
          emit("update-list");
          beforeClose();
        }
      } else {
        ElMessage.warning("返回条件和推送条件所有值都不得为空");
      }
    };
    // 提交
    const submit = () => {
      console.log(ruleForm.value);
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          createFn().catch(() => {
            loading.value = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    return {
      title,
      loading,
      visible,
      direction,
      ruleFormRef,
      ruleForm,
      rules,
      close,
      submit,
      beforeClose,
      modeList,
      insertLine,
      insertJosn,
      dataLoading,
    };
  },
});
</script>

<style lang="scss" scoped>
$height: 50px;
.drawer-main {
  height: calc(100% - 50px);
  position: relative;
  overflow: auto;
}
.drawer-footer {
  text-align: right;
  height: $height;
  line-height: $height;
}
.desc {
  color: #333;
  h3 {
    margin: 10px 0;
    color: red;
  }
  h5 {
    font-weight: bold;
    margin: 10px 0 5px 0;
  }
  code {
    margin-top: 20px;
    pre {
      padding: 10px;
      background: #f2f3f5;
    }
  }
}
table.params {
  border-collapse: collapse;
  width: 100%;
  td,
  th {
    text-align: center;
    height: 32px;
    border: #ccc solid 1px;
  }
}
</style>
